<template>
  <div v-if="!currentUser">
    名称： <input type="text" v-model="nickname" />
    <button @click="login">登录</button>
  </div>
  <div v-else>
    <div id="box" v-show="isGameStart"></div>
    <div v-show="!isGameStart">
      <div v-if="!states.isJoinRoom">
        如果你需要房间号加入房间<input type="text" v-model="roomNumber" />
      </div>
      <button v-if="!states.isCreateRoom" @click="createRoom">创建房间</button>
      <button v-if="!states.isJoinRoom" @click="joinRoom">加入房间</button>
      <button v-if="states.isJoinRoom && !states.isReady" @click="ready">
        准备
      </button>
    </div>
    <div v-show="!isGameStart">
      <!-- {{ currentUser }} -->
      <div v-for="item in peopleList" :key="item.id">
        <div>id:{{ item.id }}</div>
        <div>名称:{{ item.nickname }}</div>
        <div>准备状态:{{ item.isReady ? "是" : "否" }}</div>
      </div>
      <!-- <div>是否准备{{ states.isReady ? "是" : "否" }}</div> -->
    </div>
  </div>
</template>

<script lang="ts">
import { getClient } from "./getClient";
import { defineComponent, nextTick, onMounted, reactive, ref } from "vue";
import { MsgChat } from "./shared/protocols/MsgChat";
import { CurrentUser } from "./shared/types/CurrentUser";
import { Ball } from "./hooks/Ball";
import type { PlayerState } from "./shared/game/GameSystemState";
export default defineComponent({
  name: "Test",
  setup() {
    let client = getClient();
    let nickname = ref();
    let currentUser = ref<CurrentUser | undefined>(); //登录才有
    let isGameStart = ref(false);
    const roomNumber = ref<number | undefined>(undefined);
    const balls = reactive<any>({});
    const peopleList = ref<any>([]);
    const states = reactive({
      isReady: false,
      isCreateRoom: false,
      isJoinRoom: false,
    });
    onMounted(() => {
      // Connect at startup
      client.connect().then((v) => {
        if (!v.isSucc) {
          alert("= Client Connect Error =\n" + v.errMsg);
          return;
        }
        /* 断线重连 */
        client.flows.postDisconnectFlow.push((v) => {
          if (!v.isManual) {
            // 等待 2 秒后自动重连
            setTimeout(async () => {
              let res = await client.connect();
              // 重连也错误，弹出错误提示
              if (!res.isSucc) {
                alert("网络错误，连接已断开");
                location.reload();
              }
            }, 2000);
          }

          return v;
        });
      });
      /** 房间状态发生变化 */
      client.listenMsg("room/server/UpdateRoomState", (v) => {
        peopleList.value = v.state.players;
        if (v.destroyed) {
          alert("您已断开连接");
          location.reload();
        }
      });
      // client.listenMsg("game/server/ServerFrame", (v) => {
      // });
      // 游戏开始
      client.listenMsg("game/server/GameStart", (v) => {
        isGameStart.value = true;
        nextTick(() => {
          for (let item of v.gameState.players) {
            // 创建小球
            balls[item.id] = new Ball(
              "box",
              currentUser.value?.id as number,
              item.id == currentUser.value?.id,
              client,
              sendInfo,
              item.bgColor
            );
            balls[item.id].updatePos(item.pos);
          }
        });
      });
      client.listenMsg("Chat", (v) => {
        let { id, ...pos } = v.playerPos;
        if (id != currentUser.value?.id) balls[id].updatePos(pos);
      });
    });
    /** 登录 */
    async function login() {
      let ret = await client.callApi("Login", {
        nickname: nickname.value,
      });
      // Error
      if (!ret.isSucc) {
        alert(ret.err.message);
        return;
      } else {
        currentUser.value = ret.res?.currentUser;
      }
    }
    /** 创建房间 */
    async function createRoom() {
      let ret = await client.callApi("room/CreateRoom", {});
      // Error
      if (!ret.isSucc) {
        alert(ret.err.message);
        return;
      }
      roomNumber.value = ret.res.roomId;
      joinRoom();
      alert("房间ID为：" + ret.res.roomId);
    }
    /** 加入房间 */
    async function joinRoom() {
      let ret = await client.callApi("room/JoinRoom", {
        roomId: roomNumber.value ? +roomNumber.value : undefined,
      });
      // Error
      if (!ret.res?.isSucc) {
        alert(ret.res?.errMsg);
        return;
      }
      states.isCreateRoom = true;
      states.isJoinRoom = true;
    }
    /** 向服务端发送消息 */
    async function sendInfo(playerPos: { id: number; x: number; y: number }) {
      // const counterStore = useCounter();
      // const { auth } = storeToRefs(counterStore);
      // const adminToken = auth.value
      try {
        const result = await client //SendChat
          .callApi("Send", {
            // content: Math.random().toString(36),
            playerPos,
          });
        return result.res;
      } catch (error) {
        return error;
      }
    }
    /** 准备 */
    async function ready() {
      let ret = await client.callApi("room/SetReady", {
        isReady: true,
      });
      // Error
      if (!ret.isSucc) {
        alert(ret.err.message);
        return;
      }
      states.isReady = true;
    }
    async function leaveRoom() {
      let ret = await client.callApi("room/ExitRoom", {
        roomId: roomNumber.value as number
      });
      // Error
      if (!ret.isSucc) {
        alert(ret.err.message);
        return;
      }
    }
    window.onbeforeunload = function () {
      alert("离开页面");
      leaveRoom() 
      //功能函数
    };
    return {
      login,
      createRoom,
      joinRoom,
      ready,
      nickname,
      currentUser,
      isGameStart,
      states,
      roomNumber,
      peopleList,
    };
  },
});
</script>

<style scoped></style>
